package com.ycsj.goldmedalnewconcept.activity;

import android.animation.Animator;
import android.animation.ValueAnimator;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.inputmethod.InputMethodManager;
import android.view.ViewTreeObserver;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

import com.ycsj.goldmedalnewconcept.view.ImageInfo;
import com.ycsj.goldmedalnewconcept.view.ImagePreviewAdapter;
import com.ycsj.goldmedalnewconcept.R;

//圈子大图
public class ImagePreviewActivity extends Activity implements
		ViewTreeObserver.OnPreDrawListener, OnClickListener {
	public static final String IMAGE_INFO = "IMAGE_INFO";
	public static final String CURRENT_ITEM = "CURRENT_ITEM";
	public static final int ANIMATE_DURATION = 200;
	private int[] images = { R.drawable.b1, R.drawable.temp, R.drawable.b2,
			R.drawable.b3, R.drawable.b4 };
	private RelativeLayout rootView;
	private ImageView iv_back;
	private ImageView iv_details;
	private TextView tv_dianzan;
	private TextView tv_pinglun;
	private TextView tv_zhuanfa;
	private TextView reply_count;
	private TextView pinglun_count;
	private TextView dianzan_count;
	private TextView tv_pager;
	private ViewPager viewPager;

	private ImagePreviewAdapter imagePreviewAdapter;
	private List<ImageInfo> imageInfo;
	private int currentItem;
	private int imageHeight;
	private int imageWidth;
	private int screenWidth;
	private int screenHeight;
	private List<ImageView> mImageViewList;
	private PopupWindow popupWindow;
	private LayoutInflater mInflater;
	private PopupWindow editWindow;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_preview);
		mInflater = LayoutInflater.from(this);
		
		initView();
		initData();
		setOnListener();

		DisplayMetrics metric = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(metric);
		screenWidth = metric.widthPixels;
		screenHeight = metric.heightPixels;

		Intent intent = getIntent();
		imageInfo = (List<ImageInfo>) intent.getSerializableExtra(IMAGE_INFO);
		currentItem = intent.getIntExtra(CURRENT_ITEM, 0);

		imagePreviewAdapter = new ImagePreviewAdapter(this, imageInfo);
		// imagePreviewAdapter = new ImagePreviewAdapter(mImageViewList);
		viewPager.setAdapter(imagePreviewAdapter);

		viewPager.setCurrentItem(currentItem);
		// viewPager.getViewTreeObserver().addOnPreDrawListener(this);
		viewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
					@Override
					public void onPageSelected(int position) {
						currentItem = position;
						// tv_pager.setText(String.format("测试1", currentItem +
						// 1, imageInfo.size()));
						tv_pager.setText(currentItem + 1 + "/"
								+ imageInfo.size());
					}
				}); 
		// tv_pager.setText(String.format("测试2", currentItem + 1,
		// imageInfo.size()));
		tv_pager.setText(currentItem + 1 + "/" + imageInfo.size());
	}

	private void setOnListener() {
		iv_back.setOnClickListener(this);
		iv_details.setOnClickListener(this);
		tv_dianzan.setOnClickListener(this);
		tv_pinglun.setOnClickListener(this);
		tv_zhuanfa.setOnClickListener(this);
	}

	private void initView() {
		viewPager = (ViewPager) findViewById(R.id.viewPager);
//		tv_pager = (TextView) findViewById(R.id.tv_pager);
		rootView = (RelativeLayout) findViewById(R.id.rootView);
		iv_back = (ImageView) findViewById(R.id.iv_back);
		iv_details = (ImageView) findViewById(R.id.iv_details);
//		tv_dianzan = (TextView) findViewById(R.id.tv_dianzan);
//		tv_pinglun = (TextView) findViewById(R.id.tv_pinglun);
//		tv_zhuanfa = (TextView) findViewById(R.id.tv_zhuanfa);
//		reply_count = (TextView) findViewById(R.id.reply_count);
//		pinglun_count = (TextView) findViewById(R.id.pinglun_count);
//		dianzan_count = (TextView) findViewById(R.id.dianzan_count);

	}

	private void initData() {
		mImageViewList = new ArrayList<ImageView>();
		ImageView imageView = null;
		for (int i = 0; i < images.length; i++) {
			imageView = new ImageView(this);
			imageView.setBackgroundResource(images[i]);
			mImageViewList.add(imageView);
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.iv_back: // 返回
			finish();
			break;
				
		case R.id.iv_details: //
			View contentView = LayoutInflater.from(this).inflate(
					R.layout.popup_details, null);
			contentView.findViewById(R.id.tv_msglist).setOnClickListener(this);
			contentView.findViewById(R.id.tv_share).setOnClickListener(this);
			contentView.findViewById(R.id.tv_jubao).setOnClickListener(this);
			popupWindow = new PopupWindow(contentView,
					LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, true);
			popupWindow.setTouchable(true);
			popupWindow.setOutsideTouchable(true);
			popupWindow.setBackgroundDrawable(new ColorDrawable(
					Color.TRANSPARENT));
			popupWindow.showAsDropDown(v);
			break;
			
//		case R.id.tv_dianzan: //
//			Toast.makeText(this, "赞", Toast.LENGTH_SHORT).show();
//			break;
//			
//		case R.id.tv_pinglun: //
//			Toast.makeText(this, "评论", Toast.LENGTH_SHORT).show();
//			View editView = mInflater.inflate(R.layout.replay_input, null);
//			editWindow = new PopupWindow(editView,
//					ViewGroup.LayoutParams.MATCH_PARENT,
//					ViewGroup.LayoutParams.WRAP_CONTENT);
//			editWindow.setOutsideTouchable(true);
//			editWindow.setFocusable(true);
//			
//			editWindow
//					.setBackgroundDrawable(new ColorDrawable(Color.WHITE));
//			
//			EditText replyEdit = (EditText) editView
//					.findViewById(R.id.reply);
//			replyEdit.setFocusable(true);
//			replyEdit.requestFocus();
//			
//			Button send_msg = (Button) editView.findViewById(R.id.send_msg);
//			send_msg.setOnClickListener(new OnClickListener() {
//					
//				@Override
//				public void onClick(View v) {
//					Toast.makeText(getBaseContext(), "发送评论", Toast.LENGTH_SHORT).show();
//					editWindow.dismiss();
//				}
//			});
			
			// 以下两句不能颠倒
//			editWindow.setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED);
//			editWindow
//					.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
//			editWindow.showAtLocation(rootView, Gravity.BOTTOM, 0, 0);
//			// 显示键盘
//			final InputMethodManager imm = (InputMethodManager) getBaseContext()
//					.getSystemService(Context.INPUT_METHOD_SERVICE);
//			imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
//			
//			editWindow
//					.setOnDismissListener(new PopupWindow.OnDismissListener() {
//						@Override
//						public void onDismiss() {
//							if (imm.isActive())
//								imm.toggleSoftInput(0,
//										InputMethodManager.RESULT_SHOWN);
//						}
//					});
//			break;
			
//		case R.id.tv_zhuanfa: //
//			Toast.makeText(this, "转发", Toast.LENGTH_SHORT).show();
//			break;
//			
		case R.id.tv_msglist:
			
			Toast.makeText(this, "消息列表", Toast.LENGTH_SHORT).show();
//			popupWindow.dismiss();
			break;
			
		case R.id.tv_share:
			
			Toast.makeText(this, "分享", Toast.LENGTH_SHORT).show();
//			popupWindow.dismiss();
			break;
			
		case R.id.tv_jubao:

			Toast.makeText(this, "举报", Toast.LENGTH_SHORT).show();
//			popupWindow.dismiss();
			break;
		}
	}

	// @Override
	// public void onBackPressed() {
	// finishActivityAnim();
	// }

	/** 绘制前开始动画 */
	@Override
	public boolean onPreDraw() {
		rootView.getViewTreeObserver().removeOnPreDrawListener(this);
		final View view = imagePreviewAdapter.getPrimaryItem();
		final ImageView imageView = imagePreviewAdapter.getPrimaryImageView();
		computeImageWidthAndHeight(imageView);

		final ImageInfo imageData = imageInfo.get(currentItem);
		final float vx = imageData.imageViewWidth * 1.0f / imageWidth;
		final float vy = imageData.imageViewHeight * 1.0f / imageHeight;
		ValueAnimator valueAnimator = ValueAnimator.ofFloat(0, 1.0f);
		valueAnimator
				.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
					@Override
					public void onAnimationUpdate(ValueAnimator animation) {
						long duration = animation.getDuration();
						long playTime = animation.getCurrentPlayTime();
						float fraction = duration > 0 ? (float) playTime
								/ duration : 1f;
						if (fraction > 1)
							fraction = 1;
						view.setTranslationX(evaluateInt(fraction,
								imageData.imageViewX + imageData.imageViewWidth
										/ 2 - imageView.getWidth() / 2, 0));
						view.setTranslationY(evaluateInt(fraction,
								imageData.imageViewY
										+ imageData.imageViewHeight / 2
										- imageView.getHeight() / 2, 0));
						view.setScaleX(evaluateFloat(fraction, vx, 1));
						view.setScaleY(evaluateFloat(fraction, vy, 1));
						view.setAlpha(fraction);
						rootView.setBackgroundColor(evaluateArgb(fraction,
								Color.TRANSPARENT, Color.BLACK));
					}
				});
		addIntoListener(valueAnimator);
		valueAnimator.setDuration(ANIMATE_DURATION);
		valueAnimator.start();
		
		return true;
	}
	
	/** activity的退场动画 */
	public void finishActivityAnim() {
		final View view = imagePreviewAdapter.getPrimaryItem();
		final ImageView imageView = imagePreviewAdapter.getPrimaryImageView();
		computeImageWidthAndHeight(imageView);

		final ImageInfo imageData = imageInfo.get(currentItem);
		final float vx = imageData.imageViewWidth * 1.0f / imageWidth;
		final float vy = imageData.imageViewHeight * 1.0f / imageHeight;
		final ValueAnimator valueAnimator = ValueAnimator.ofFloat(0, 1.0f);
		valueAnimator
				.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
					@Override
					public void onAnimationUpdate(ValueAnimator animation) {
						long duration = animation.getDuration();
						long playTime = animation.getCurrentPlayTime();
						float fraction = duration > 0 ? (float) playTime
								/ duration : 1f;
						if (fraction > 1)
							fraction = 1;
						view.setTranslationX(evaluateInt(fraction, 0,
								imageData.imageViewX + imageData.imageViewWidth
										/ 2 - imageView.getWidth() / 2));
						view.setTranslationY(evaluateInt(fraction, 0,
								imageData.imageViewY
										+ imageData.imageViewHeight / 2
										- imageView.getHeight() / 2));
						view.setScaleX(evaluateFloat(fraction, 1, vx));
						view.setScaleY(evaluateFloat(fraction, 1, vy));
						view.setAlpha(1 - fraction);
						rootView.setBackgroundColor(evaluateArgb(fraction,
								Color.BLACK, Color.TRANSPARENT));
					}
				});
		addOutListener(valueAnimator);
		valueAnimator.setDuration(ANIMATE_DURATION);
		valueAnimator.start();
	}

	/** 计算图片的宽高 */
	private void computeImageWidthAndHeight(ImageView imageView) {

		// 获取真实大小
		Drawable drawable = imageView.getDrawable();
		int intrinsicHeight = drawable.getIntrinsicHeight();
		int intrinsicWidth = drawable.getIntrinsicWidth();
		// 计算出与屏幕的比例，用于比较以宽的比例为准还是高的比例为准，因为很多时候不是高度没充满，就是宽度没充满
		float h = screenHeight * 1.0f / intrinsicHeight;
		float w = screenWidth * 1.0f / intrinsicWidth;
		if (h > w)
			h = w;
		else
			w = h;

		// 得出当宽高至少有一个充满的时候图片对应的宽高
		imageHeight = (int) (intrinsicHeight * h);
		imageWidth = (int) (intrinsicWidth * w);
	}

	/** 进场动画过程监听 */
	private void addIntoListener(ValueAnimator valueAnimator) {
		valueAnimator.addListener(new Animator.AnimatorListener() {
			@Override
			public void onAnimationStart(Animator animation) {
				rootView.setBackgroundColor(0x0);
			}

			@Override
			public void onAnimationEnd(Animator animation) {
			}

			@Override
			public void onAnimationCancel(Animator animation) {
			}

			@Override
			public void onAnimationRepeat(Animator animation) {
			}
		});
	}

	/** 退场动画过程监听 */
	private void addOutListener(ValueAnimator valueAnimator) {
		valueAnimator.addListener(new Animator.AnimatorListener() {
			@Override
			public void onAnimationStart(Animator animation) {
				rootView.setBackgroundColor(0x0);
			}

			@Override
			public void onAnimationEnd(Animator animation) {
				finish();
				overridePendingTransition(0, 0);
			}

			@Override
			public void onAnimationCancel(Animator animation) {
			}

			@Override
			public void onAnimationRepeat(Animator animation) {
			}
		});
	}

	/** Integer 估值器 */
	public Integer evaluateInt(float fraction, Integer startValue,
			Integer endValue) {
		int startInt = startValue;
		return (int) (startInt + fraction * (endValue - startInt));
	}

	/** Float 估值器 */
	public Float evaluateFloat(float fraction, Number startValue,
			Number endValue) {
		float startFloat = startValue.floatValue();
		return startFloat + fraction * (endValue.floatValue() - startFloat);
	}

	/** Argb 估值器 */
	public int evaluateArgb(float fraction, int startValue, int endValue) {
		int startA = (startValue >> 24) & 0xff;
		int startR = (startValue >> 16) & 0xff;
		int startG = (startValue >> 8) & 0xff;
		int startB = startValue & 0xff;

		int endA = (endValue >> 24) & 0xff;
		int endR = (endValue >> 16) & 0xff;
		int endG = (endValue >> 8) & 0xff;
		int endB = endValue & 0xff;

		return (startA + (int) (fraction * (endA - startA))) << 24//
				| (startR + (int) (fraction * (endR - startR))) << 16//
				| (startG + (int) (fraction * (endG - startG))) << 8//
				| (startB + (int) (fraction * (endB - startB)));
	}

}
